package com.binguo.api.controller;


import com.binguo.api.form.TencentApiForm;
import com.binguo.api.result.Result;
import com.binguo.api.result.ResultGenerator;
import com.binguo.api.service.RedisLockService;
import com.binguo.api.service.TencentApiService;

import com.binguo.common.util.ShellUtil;
import com.binguo.model.model.ProductYpType;

import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.cvm.v20170312.CvmClient;
import com.tencentcloudapi.cvm.v20170312.models.*;
import org.codehaus.groovy.runtime.dgmimpl.arrays.FloatArrayGetAtMetaMethod;
import org.omg.PortableServer.SERVANT_RETENTION_POLICY_ID;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.web.bind.annotation.*;

import java.util.*;
import java.util.concurrent.ScheduledExecutorService;

@RestController
public class TencentApiController {

    public static String secretld = "AKIDud6KAoFVVHrDLFCLYXIp8B0aCZpql7NN";
    public static String secretKey = "tXv3wZ0B9sMwNacR2PYUCftsfDk49yYs";
    //public static String secretld = "AKIDOa1ECvChla3IMBl7IFxQfhT0KyMUt4Xl";
    //public static String secretKey = "8FArLZaNvPduxkIepmTwCF4vYEgspY3p";
    public static String USER_NAME = "root";
    public static String PASS_WORD = "yunpengai.306";
    private static TencentApiForm tencentApiForm = new TencentApiForm();

    private static Logger logger = LoggerFactory.getLogger(TencentApiController.class);
    private static String instanceChargeType = "SPOTPAID";
    private static String instanceType = "GN6S.LARGE20";
    private static String imageId = "img-9qabwvbn";
    private static String marketTpye = "spot";
    private static String maxPrice = "1.43";
    private static String zone = "ap-shanghai-2";
    private static String diskType = "CLOUD_BASIC";//磁盘类型
    private static Integer diskSize = 200;//磁盘大小
    private static String vpcId = "vpc-gbmm3yrd";//所属网络
    private static String subnetId = "subnet-g63w362d";//子网id
    private static String internetChargeType = "TRAFFIC_POSTPAID_BY_HOUR";//网络计费模式
    private static Integer internetMaxBandwidthOut = 100;//带宽大小
    private static boolean publicIpAssigned = true;//是否分配公网ip
    public String servers = "";
    @Autowired
    private TencentApiService tencentApiService;
    @Autowired
    private RedisLockService redisLockService;

    static String ip = "";
    /**
     * 创建实例
     * @param instanceChargeType
     * 实例付费类型   instanceChargeType
     *       PREPAID：预付费，即包年包月
     *       POSTPAID_BY_HOUR：按小时后付费
     *       CDHPAID：独享子机（基于专用宿主机创建，宿主机部分的资源不收费）
     *       SPOTPAID：竞价付费   默认竞价付费
     *
     * @param zone   实例所属的[可用区]   默认 ap-sahnghai-2
     * @param instanceType  实例机型   默认  GN6S.LARGE20
     * @param imageId  系统镜像id :  默认   img-9qabwvbn(centos 7)
     * @param marketType   instanceChargeType时 marketType必填spot(当前默认值)
     * @param maxPrice   竞价出价   不能低于当前竞价
     * @return
     * @throws Exception
     */
    @GetMapping(value = "/api/tencent/RunInstances")
    public Result RunInstances(String instanceChargeType,String zone,
                               String instanceType,String imageId,
                               String marketType,String maxPrice
                              ){
        if(null == instanceChargeType){
            instanceChargeType = this.instanceChargeType;
        }if(null == zone){
            zone = this.zone;
        }if(null == instanceType){
            instanceType = this.instanceType;
        }if(null == imageId){
            imageId = this.imageId;
        }if(null == marketType){
            marketType = this.marketTpye;
        }if(null == maxPrice){
            maxPrice = this.maxPrice;
        }
        try{
            Credential cred = new Credential(secretld, secretKey);
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("cvm.tencentcloudapi.com");
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            CvmClient client = new CvmClient(cred, "ap-shanghai", clientProfile);
            String params = "{\"InstanceChargeType\":"+instanceChargeType+"," +
                    "\"Placement\":{\"Zone\":"+zone+"}," +
                    "\"InstanceType\":"+instanceType+"," +
                    "\"ImageId\":"+imageId+"," +
                    "\"SystemDisk\":{\"DiskSize\":"+diskSize+"},"+
                   /* "\"VirtualPrivateCloud\":{\"VpcId\":"+vpcId+",\"SubnetId\":"+subnetId+"}," +*/
                    "\"InternetAccessible\":{\"InternetChargeType\":"+internetChargeType+",\"InternetMaxBandwidthOut\":"+internetMaxBandwidthOut+",\"PublicIpAssigned\":"+publicIpAssigned+"}," +
                    "\"InstanceMarketOptions\":{\"MarketType\":"+marketType+"," +
                    "\"SpotOptions\":{\"MaxPrice\":"+maxPrice +"," +
                    "\"SpotInstanceType\":\"one-time\"}}}";
            /*String params = "{\"InstanceChargeType\":"+instanceChargeType+"," +
                    "\"Placement\":{\"Zone\":"+zone+"}," +
                    "\"InstanceType\":"+instanceType+"," +
                    "\"ImageId\":"+imageId+"," +
                    "\"InstanceMarketOptions\":{\"MarketType\":"+marketType+"," +
                    "\"SpotOptions\":{\"MaxPrice\":"+maxPrice +"," +
                    "\"SpotInstanceType\":\"one-time\"}}}";*/
            RunInstancesRequest req = RunInstancesRequest.fromJsonString(params, RunInstancesRequest.class);
            RunInstancesResponse resp = client.RunInstances(req);
            return ResultGenerator.genSuccessResult(resp);
        } catch (TencentCloudSDKException e) {
            return ResultGenerator.genFailResult(e.toString());
        }
    }

    /**
     * 查看实例列表
      instances   实例id   以数组方式传入
     * @return
     */
    @PostMapping(value = "/api/tencent/describelInstances")
    public Result describelInstances(@RequestBody TencentApiForm tencentApiForm) {
        try{
            String params = "";
            if(null == tencentApiForm.getInstances()){
                 params = "{}";
            }else{
                String instance = StringArrayToString(tencentApiForm.getInstances());
                params = "{\"InstanceIds\":"+instance+"}";
            }
            Credential cred = new Credential(secretld, secretKey);
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("cvm.tencentcloudapi.com");
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            CvmClient client = new CvmClient(cred, "ap-shanghai", clientProfile);
            DescribeInstancesRequest req = DescribeInstancesRequest.fromJsonString(params, DescribeInstancesRequest.class);
            DescribeInstancesResponse resp = client.DescribeInstances(req);
            return ResultGenerator.genSuccessResult(resp);
        } catch (TencentCloudSDKException e) {
            return ResultGenerator.genFailResult(e.toString());
        }
    }

    /**
     * 退还实例
      instances  实例id   多个以数组方式传入
     * @return
     */
    @PostMapping(value = "/api/tencent/terminateInstance")
    public Result describelInstance(@RequestBody TencentApiForm tencentApiForm){
        try{
            String params = "";
            if(null == tencentApiForm.getInstances()){
                return ResultGenerator.genFailResult("未指定实例id");
            }else{
                String instance = StringArrayToString(tencentApiForm.getInstances());
                params = "{\"InstanceIds\":"+instance+"}";
            }
            Credential cred = new Credential(secretld, secretKey);
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("cvm.tencentcloudapi.com");
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            CvmClient client = new CvmClient(cred, "ap-shanghai", clientProfile);
            TerminateInstancesRequest req = TerminateInstancesRequest.fromJsonString(params, TerminateInstancesRequest.class);
            TerminateInstancesResponse resp = client.TerminateInstances(req);
            return ResultGenerator.genSuccessResult(resp);
        } catch (TencentCloudSDKException e) {
            return ResultGenerator.genFailResult(e.toString());
        }
    }

    /**
     * 启动实例
    instances   实例id   多个以数组方式传入
     * @return
     */
    @PostMapping(value = "/api/tencent/startInstance")
    public Result startInstance(@RequestBody TencentApiForm tencentApiForm){
        try{
            String params = "";
            if(null == tencentApiForm.getInstances()){
                return ResultGenerator.genFailResult("未指定实例id");
            }else{
                String instance = StringArrayToString(tencentApiForm.getInstances());
                params = "{\"InstanceIds\":"+instance+"}";
            }
            Credential cred = new Credential(secretld, secretKey);
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("cvm.tencentcloudapi.com");
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            CvmClient client = new CvmClient(cred, "ap-shanghai", clientProfile);
            StartInstancesRequest req = StartInstancesRequest.fromJsonString(params, StartInstancesRequest.class);
            StartInstancesResponse resp = client.StartInstances(req);
            System.out.println();
            return ResultGenerator.genSuccessResult(resp);
        } catch (TencentCloudSDKException e) {
            return ResultGenerator.genFailResult(e.toString());
        }
    }

    /**
     * 关闭实例
     *instances   关闭实例id,多个id以数组形式传入
     *                    下面几个参数有问题，暂时先不用
      forceStop   是否在正常关闭失败后选择强制关闭实例   (TRUE/SOFT_FIRST)  默认FALSE
      stopType    关机类型   (SOFT:软关机/HARD:强制关机/SOFT_FIRST:软关机失败后强制关机)  默认SOFT
      stoppedMode  按量计费关机收费模式   (KEEP_CHARGING:关机继续收费/STOP_CHARGING:关机停止收费)    默认 KEEP_CHARGING
     * @return
     */
    @PostMapping(value = "/api/tencent/stopInstance")
    public Result stopInstance(@RequestBody TencentApiForm tencentApiForm){
        try{
            /*if(null == tencentApiForm.getForceStop()){
                tencentApiForm.setForceStop(false);
            }
            if(null == tencentApiForm.getStopType()){
                tencentApiForm.setStopType("SOFT");
            }*/
            String params = "";
            if(null == tencentApiForm.getInstances()){
                return ResultGenerator.genFailResult("未指定实例id");
            }else{
                String instance = StringArrayToString(tencentApiForm.getInstances());
                params = "{\"InstanceIds\":"+instance+"}";
            }
            Credential cred = new Credential(secretld, secretKey);
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("cvm.tencentcloudapi.com");
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            CvmClient client = new CvmClient(cred, "ap-shanghai", clientProfile);

            //String params = "{\"InstanceIds\":"+instance+",\"ForceStop\":"+tencentApiForm.getForceStop()+",\"StopType\":"+tencentApiForm.getStopType()+",\"StoppedMode\":"+tencentApiForm.getStoppedMode()+"}";
            StopInstancesRequest req = StopInstancesRequest.fromJsonString(params, StopInstancesRequest.class);
            StopInstancesResponse resp = client.StopInstances(req);

            return ResultGenerator.genSuccessResult(resp);
        } catch (TencentCloudSDKException e) {
            return ResultGenerator.genFailResult(e.toString());
        }
    }

    /**
     * 重启实例
     instances   重启实例id,多个id以数组形式传入
     下面几个参数有问题，暂时先不用
      forceReboot  是否在正常重启失败后选择强制重启实例   (TRUE/FALSE)  默认FALSE
      stopType   重启类型   (SOFT:软重启/HARD:强制重启/SOFT_FIRST:软重启失败后强制重启)  默认SOFT
     * @return
     */
    @PostMapping(value = "/api/tencent/rebootInstance")
    public Result rebootInstance(@RequestBody TencentApiForm tencentApiForm){
        try{
            /*if(null == forceReboot){
                forceReboot = false;
            }
            if(null == stopType){
                stopType = "SOFT";
            }*/
            String params = "";
            if(null == tencentApiForm.getInstances()){
                return ResultGenerator.genFailResult("未指定实例id");
            }else{
                String instance = StringArrayToString(tencentApiForm.getInstances());
                params = "{\"InstanceIds\":"+instance+"}";
            }
            Credential cred = new Credential(secretld, secretKey);
            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("cvm.tencentcloudapi.com");
            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);
            CvmClient client = new CvmClient(cred, "ap-shanghai", clientProfile);

            //String params = "{\"InstanceIds\":"+instances+",\"ForceReboot\":"+forceReboot+",\"StopType\":"+stopType+"}";
            RebootInstancesRequest req = RebootInstancesRequest.fromJsonString(params,RebootInstancesRequest.class);
            RebootInstancesResponse resp = client.RebootInstances(req);
            return ResultGenerator.genSuccessResult(resp);
        } catch (TencentCloudSDKException e) {
            return ResultGenerator.genFailResult(e.toString());
        }
    }

    public String StringArrayToString(String [] array){
        String instance = "[";
        for(int i = 0;i < array.length;i++){
            instance += "\"";
            instance += array[i];
            instance += "\"";
            if (i != array.length-1){
                instance += ",";
            }
        }
        instance += "]";
        return instance;
    }

    /**
     * 早上6点创建实例并更新数据库ProductYpType表
     */
    @Scheduled(cron = "0 0 6 ? * *")
    public void createTencentServers(){

        String key = "createTencentServers";
        String uuid = UUID.randomUUID().toString();
        //基于redis的分布式锁，过期时间为10秒，如果当前锁不存在则客户端拿到锁，如果存在则不做操作
        boolean lock = redisLockService.setLockOrder(key, 10000, uuid);
        if (lock) {
            //每天早上5点新建腾讯云服务器
            Result<RunInstancesResponse> result = RunInstances(this.instanceChargeType,this.zone,this.instanceType
                    ,"img-6aym7s7f",this.marketTpye,this.maxPrice);
            RunInstancesResponse resp = result.getData();
            String instanceId = resp.getInstanceIdSet()[0];
            logger.info("创建腾讯云实例成功,实例id:"+instanceId);
            servers = instanceId;
            String instance[] = new String[1];
            instance[0] =  instanceId;
            tencentApiForm.setInstances(instance);
        }
    }
    @Scheduled(cron = "0 5 6 ? * *")
    public void doRepass(){
        Result result = repassInstance(tencentApiForm);
        logger.info("修改密码结果:"+result);
    }
//    @Scheduled(cron = "0 25 15 ? * *")
    public void getServerIp(){
        if(TencentApiController.tencentApiForm !=  null){
            logger.info("查询ip");
            Result<DescribeInstancesResponse> result = describelInstances(TencentApiController.tencentApiForm);
            DescribeInstancesResponse  resp = result.getData();
            String publicIp = "";
            if(!(resp.getInstanceSet().length<= 0)){
                ip  = resp.getInstanceSet()[0].getPrivateIpAddresses()[0];
                publicIp = resp.getInstanceSet()[0].getPublicIpAddresses()[0];
                logger.info(publicIp);
            }
            if(ip != null && !ip.equals("")){
                logger.info("查询实例成功,实例ip:"+ip);
                boolean flag = ShellUtil.doShell("Administrator",PASS_WORD,ip);
                if(flag){
                    try{
                        ProductYpType productYpType = tencentApiService.selectById(14);
                        productYpType.setRecUrl("http://"+ip+":8099/sendMsg9005");
                        Integer count = tencentApiService.updateProductYpType(productYpType);
                        if(count != null && count > 0){
                            logger.info("数据库更新成功。");
                        }
                    }catch(Exception e){
                        logger.info(e.getMessage());
                    }
                }else{
                    logger.info("执行远程连接脚本失败");
                }


            }
        }

    }


    /**
     * 晚上8点关闭实例
     */
    @Scheduled(cron = "0 0 20 * * ?")
    public void deleteTencentServers(){
        String key = "deleteTencentServers";
        String uuid = UUID.randomUUID().toString();
        boolean lock = redisLockService.setLockOrder(key, 10000, uuid);
        if (lock) {
            if(servers == null ){
                logger.info("实例未创建");
            }else{
                TencentApiForm tencentApiForm = new TencentApiForm();
                String instance[] = new String[1];
                instance[0] =  servers;
                tencentApiForm.setInstances(instance);
                Result result = describelInstance(tencentApiForm);
                logger.info(result.toString());
                servers = "";
                tencentApiForm = null;
            }
        }
    }

    /**
     * 查看实例列表
     instances   实例id   以数组方式传入
     * @return
     */
    @PostMapping(value = "/api/tencent/repassInstances")
    public Result repassInstance(@RequestBody TencentApiForm tencentApiForm) {
        try{
            String params = "";
            if(null == tencentApiForm.getInstances()){
                return ResultGenerator.genFailResult("未指定实例id");
            }else{
                String instance = StringArrayToString(tencentApiForm.getInstances());
                params = "{\"InstanceIds\":"+instance+",\"Password\":"+PASS_WORD+",\"UserName\":\"Administrator\",\"ForceStop\":true}";
            }
            Credential cred = new Credential("AKIDud6KAoFVVHrDLFCLYXIp8B0aCZpql7NN", "tXv3wZ0B9sMwNacR2PYUCftsfDk49yYs");

            HttpProfile httpProfile = new HttpProfile();
            httpProfile.setEndpoint("cvm.tencentcloudapi.com");

            ClientProfile clientProfile = new ClientProfile();
            clientProfile.setHttpProfile(httpProfile);

            CvmClient client = new CvmClient(cred, "ap-shanghai", clientProfile);
            ResetInstancesPasswordRequest req = ResetInstancesPasswordRequest.fromJsonString(params, ResetInstancesPasswordRequest.class);

            ResetInstancesPasswordResponse resp = client.ResetInstancesPassword(req);

            System.out.println(ResetInstancesPasswordRequest.toJsonString(resp));
            return ResultGenerator.genSuccessResult(resp);
        } catch (TencentCloudSDKException e) {
            System.out.println(e.toString());
            return ResultGenerator.genFailResult(e.toString());
        }

    }



}
